#!/usr/bin/python
# -*- coding: utf-8 -*-

import psycopg2
import sys
import json
import cgi
import datetime
import db_conf
con = None
try:
    qform = cgi.FieldStorage()
    compound_id = qform.getvalue('compound_id')
    config = db_conf.getConfig('metabvis.conf')
    con = psycopg2.connect(host=db_conf.getDBHost(config), database=db_conf.getDBName(config), port=db_conf.getDBPort(config), user=db_conf.getUser(config), password=db_conf.getPassword(config))
    cur = con.cursor()
    sel_compound_spectral = 'select s.spectrum_id, s.ri, so.spectrum_origin_text, date(s.time_added), user_comment from compound_spectrum cs, spectrum s, spectrum_origin so where s.archived = 0 and compound_id = %s and cs.spectrum_id = s.spectrum_id and s.spectrum_origin_id = so.spectrum_origin_id' %(compound_id)
    cur.execute(sel_compound_spectral)          
    rows = cur.fetchall()
    print "Content-type: text/html;charset=utf-8\r\n"
    pa = {}
    pa['compoundSpectralData'] = []
    pa['spectralAnnotationData'] = []
    for row in rows:
        pi = []
        ct = 0
        ppath = "N/A"
        spid = row[0]
        comment = "None"
        for r in range(len(row)):
            ct = ct + 1
            if (ct < len(row)):	
                pi.append(str(row[r]))
        if (row[4] != None):
            comment = row[4]
        
        if (ct == len(row)):
            cur.execute("SELECT proprietary_path FROM spectrum s LEFT JOIN chromatogram c USING (chromatogram_id) WHERE spectrum_id = " + str(spid))
            ppath = cur.fetchone()[0]
            chromFile = "Chrom" 
            if (ppath == None or ppath == ""):
                ppath = "NONE"
                chromFile = "N/A"
            pi.append("<a title='" + comment + "' href='#'>Comment" + "</a>" + "&nbsp;<a title='" + ppath + "' href='#'>" + chromFile + "</a>" + "&nbsp;<a href=javascript:delete_spectrum('" + str(row[0]) + "')>Delete</a>")
        
        pa['compoundSpectralData'].append(pi)
    sel_spectrum_annotation = 'select mz, formula, mass_isotopomer_max, precursor_atoms_retained, confirmed_by_labeling, comment, id from spectrum_annotation where archived = 0 and compound_id = ' + compound_id
    cur.execute(sel_spectrum_annotation)
    srows = cur.fetchall()
    for srow in srows:
        spi = []
        rl = len(srow)
        ct = 0
        for sr in range(len(srow)-1):
            ct = ct + 1
            spi.append(str(srow[sr]))
        #print "%i %i" %(ct, rl)
        if (ct == rl-1):
	  spi.append("<a href=javascript:update_spectrum_annotation('" + str(srow[rl-1]) + "')>Update &nbsp;</a>"+ "<a href=javascript:delete_spectrum_annotation('" + str(srow[rl-1]) + "')>Delete</a>")
	  spi.append(srow[rl-1])
        pa['spectralAnnotationData'].append(spi)
    print json.dumps(pa)
except psycopg2.DatabaseError, e:
    print 'Error %s' % e    
    sys.exit(1)    
finally:
    if con:
        con.close()
